package com.example.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.commons.SysConstant;
import com.example.entity.Order;
import com.example.mapper.OrderMapper;
import com.example.service.OrderService;
import com.example.utils.SnowFlakeUtils;
import com.google.common.collect.Lists;
import jakarta.annotation.Resource;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import org.springframework.stereotype.Service;

/**
 * 订单表(Order)表服务实现类
 *
 * @author 游家纨绔
 * @since 2023-09-09 19:40:00
 */
@Service("tOrderService")
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

	@Resource
	private OrderMapper orderMapper;

	// 创建订单
	@Override
	public Order createOrder() {
		// 这里定义订单的随机金额 [0, 1)
		DecimalFormat decimalFormat = new DecimalFormat("#.##");
		String orderNo = decimalFormat.format(new Random().nextDouble(1));
		double parseDouble = Double.parseDouble(orderNo);
		// 1、生成订单编号
		Order order = Order.builder()
		                   .subject("付款数据测试")
		                   .orderNo(String.valueOf(SnowFlakeUtils.nextId()))
		                   .totalAmount(parseDouble)
		                   .status(SysConstant.WAIT_BUYER_PAY)
		                   .createTime(new Timestamp(new Date().getTime()))
		                   .updateTime(new Timestamp(new Date().getTime()))
		                   // 随机生成其中的一种支付方式
		                   .payType(Lists.newArrayList("ZFB", "WX", "YL").get(new Random().nextInt(0, 3)))
		                   .build();

		// 调用 mapper 写入数据
		orderMapper.insert(order);
		return order;
	}

	// 根据商户的订单编号查询订单
	@Override
	public Order getByTradeNo(String outTradeNo) {
		return orderMapper.selectOne(Wrappers.<Order>lambdaQuery().eq(Order::getOrderNo, outTradeNo));
	}

	// 更新订单状态
	@Override
	public void updateOrderStatus(Order order, String tradeSuccess) {
		if (Objects.isNull(order.getId()) && Objects.nonNull(order.getOrderNo())) {
			orderMapper.update(Order.builder().status(tradeSuccess).build(), Wrappers.<Order>lambdaUpdate().eq(Order::getOrderNo, order.getOrderNo()));
		} else {
			order.setStatus(tradeSuccess);
			orderMapper.updateById(order);
		}
	}

	// 查询所有订单
	@Override
	public List<Order> queryListOrderAll() {
		return orderMapper.selectDictAll();
	}
}
